//
//  HPAddViewController.m
//  HappyPenguin
//
//  Created by zhuangyihang on 1/13/16.
//  Copyright © 2016 zhuangyihang. All rights reserved.
//

#import "HPAddViewController.h"
#import <UITextView+Placeholder.h>
#import "UIViewController+DismissKeyboard.h"
#import "ToDoCellView.h"

static const NSInteger kViewMarginLeft = 15;
static const NSInteger kSpeakBottomViewHeight = 40;

static const NSInteger kPictureMaxCol = 4;
static const NSInteger kPictureInterval = 10;

@interface HPAddViewController ()

@property (nonatomic, strong) UIScrollView *mainScrollView;
@property (nonatomic, strong) UIView *picturePanel;
@property (nonatomic, strong) UIView *contentPanel;
@property (nonatomic, strong) UIView *cellPanel;

@property (nonatomic, strong) UILabel *tipLabel;
@property (nonatomic, strong) UITextField *nameLabel;

@property (nonatomic, strong) NSMutableArray *pictures;

@end

@implementation HPAddViewController

- (id)init{
    self = [super init];
    if (self) {
        self.isAdd = YES;
        
        self.pictures = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self addBackButton:nil];
    [self setupForDismissKeyboard];
    
    [self setupUI];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - Private
- (void)setupUI{
    if (self.isAdd) {
        [self setBaseNavigationBarTitle:@"写跟进"];
        [self.baseRightButton setTitle:@"保存" forState:UIControlStateNormal];
        [self addRightButtonSelector:@selector(finish)];
        
        [self setupSpeakBottomView];
        [self setupScrollView];
        
    }
}

- (void)setupScrollView{
    self.mainScrollView = [UIScrollView new];
    [self.baseContentView addSubview:self.mainScrollView];
    [self.mainScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.baseContentView);
        make.bottom.equalTo(self.baseContentView).offset(-kSpeakBottomViewHeight);
        make.width.centerX.equalTo(self.baseContentView);
    }];
    
    UIView *container = [UIView new];
    [self.mainScrollView addSubview:container];
    [container mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.mainScrollView);
        make.width.equalTo(self.mainScrollView);
    }];
    
    self.nameLabel = [UITextField new];
    [container addSubview:self.nameLabel];
    self.nameLabel.placeholder = @"搜索用户";
    
    UIImageView *searchIcon = [UIImageView new];
    [container addSubview:searchIcon];
    [searchIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.nameLabel);
        make.left.equalTo(container).offset(kViewMarginLeft);
    }];
    searchIcon.image = [UIImage imageNamed:@"Button_TodoSearch"];
    
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@40);
        make.top.equalTo(container);
        make.left.equalTo(searchIcon.mas_right).offset(5);
    }];
    
    UIView *sep = [UIView new];
    [container addSubview:sep];
    [sep mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.centerX.equalTo(container);
        make.height.equalTo(@1);
        make.top.equalTo(self.nameLabel.mas_bottom);
    }];
    sep.backgroundColor = [UIConstants getSeperatorColor];
    
    self.tipLabel = [UILabel new];
    [container addSubview:self.tipLabel];
    [self.tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(container).offset(kViewMarginLeft);
        make.right.equalTo(container).offset(-kViewMarginLeft);
        make.top.equalTo(sep.mas_bottom).offset(5);
    }];
    self.tipLabel.font = [UIConstants getFont:14];
    self.tipLabel.numberOfLines = 0;
    self.tipLabel.text = @"我是快消品供应商，现在在做月饼的销售工作。我们是在南方，广西广东边界上的一个3、4线小城市，这里的人要买月饼是超过80%的人非五仁月饼不买，因为这是广式月饼的传统口味。其次还有叉烧、火腿月饼也是畅销品，这两年开始流五仁行金腿月饼，在五仁馅里添加了金腿和肉松，我们销售的某个品种甚至带有酒香。咬下去是松脆绵软香飘四溢，极其美味的。";
    
    //选项
    self.cellPanel = [UIView new];
    [container addSubview:self.cellPanel];
    [self.cellPanel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.tipLabel.mas_bottom);
        make.width.centerX.equalTo(container);
    }];
    
    //跟进内容和语音
    self.contentPanel = [UIView new];
    [container addSubview:self.contentPanel];
    [self.contentPanel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.cellPanel.mas_bottom);
        make.width.centerX.equalTo(container);
    }];
    
    //跟进图片
    self.picturePanel = [UIView new];
    [container addSubview:self.picturePanel];
    [self.picturePanel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentPanel.mas_bottom);
        make.width.centerX.equalTo(container);
    }];
    
    [container mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.picturePanel.mas_bottom);
    }];
    
    [self refreshPicturePanel];
    [self refreshContentPanel];
    [self refreshCellPanel];
}


- (void)setupSpeakBottomView{
    UIView *v = [UIView new];
    [self.baseContentView addSubview:v];
    [v mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.centerX.bottom.equalTo(self.baseContentView);
        make.height.mas_equalTo(kSpeakBottomViewHeight);
    }];
    
    
    
    UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];
    [v addSubview:b];
    [b mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(v);
    }];
    [b setImage:[UIImage imageNamed:@"ToDo_Speak"] forState:UIControlStateNormal];
    [b setTitle:@"按住说话" forState:UIControlStateNormal];
    [b setTitleColor:[UIConstants getAppColor] forState:UIControlStateNormal];
    
    CGSize imageSize = b.imageView.frame.size;
    b.titleEdgeInsets = UIEdgeInsetsMake(0.0, - imageSize.width,0, 0.0);
    
    // raise the image and push it right so it appears centered
    //  above the text
    CGSize titleSize = b.titleLabel.frame.size;
    b.imageEdgeInsets = UIEdgeInsetsMake(0, 0.0, 0.0, - titleSize.width);
    
    UIView *sep = [UIView new];
    [v addSubview:sep];
    [sep mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.top.centerX.equalTo(v);
        make.height.equalTo(@1);
    }];
    sep.backgroundColor = [UIConstants getSeperatorColor];
}

#pragma mark - Refresh Data
- (void)refreshPicturePanel{
    WS(ws);
    [self.picturePanel removeAllSubviews];
    
    UIView *sep = [UIView new];
    [self.picturePanel addSubview:sep];
    [sep mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.top.centerX.equalTo(self.picturePanel);
        make.height.equalTo(@1);
    }];
    sep.backgroundColor = [UIConstants getSeperatorColor];
    
    CGFloat width = ([UIScreen mainScreen].bounds.size.width - 2 * kViewMarginLeft - (kPictureMaxCol-1)*kPictureInterval)/kPictureMaxCol;
    
    UIView *lastView = nil;
    for (int i = 0; i < self.pictures.count+1; i++) {
        UIImageView *v = [UIImageView new];
        [self.picturePanel addSubview:v];
        
        int col = i % kPictureMaxCol;
        int row = i / kPictureMaxCol;
        
        [v mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.mas_equalTo(width);
            make.left.equalTo(self.picturePanel).offset(col*(width+kPictureInterval)+kViewMarginLeft);
            make.top.equalTo(self.picturePanel).offset(row*(width+kPictureInterval) + kViewMarginLeft);
        }];
        v.contentMode = UIViewContentModeScaleAspectFill;
        v.clipsToBounds = YES;
        
        lastView = v;
        
        if (i == self.pictures.count) {
            v.userInteractionEnabled = YES;
            UITapGestureRecognizer *tap = [UITapGestureRecognizer bk_recognizerWithHandler:^(UIGestureRecognizer *sender, UIGestureRecognizerState state, CGPoint location) {
                UIActionSheet *sheet = [UIActionSheet bk_actionSheetWithTitle:nil];
                [sheet bk_addButtonWithTitle:@"从照片库里选择" handler:^{
                    [ws openImagePicker:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
                }];
                [sheet bk_addButtonWithTitle:@"摄像" handler:^{
                    [ws openImagePicker:UIImagePickerControllerSourceTypeCamera];                    
                }];
                [sheet bk_setCancelBlock:^{
                    
                }];
                [sheet showInView:ws.view];
            }];
            [v addGestureRecognizer:tap];
            
            v.image = [UIImage imageNamed:@"ToDo_AddPicture"];
        }else{
            v.image = self.pictures[i];
        }
    }
    
    [self.picturePanel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(lastView.mas_bottom).offset(kViewMarginLeft);
    }];
}

- (void)refreshContentPanel{
    WS(ws);
    
    [self.contentPanel removeAllSubviews];
    
    UITextView *v = [UITextView new];
    [self.contentPanel addSubview:v];
    [v mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.contentPanel).offset(-kViewMarginLeft*2);
        make.centerX.top.equalTo(self.contentPanel);
        make.height.greaterThanOrEqualTo(@30);
    }];
    v.placeholder = @"写跟进内容";
    [v setScrollEnabled:NO];
    
    UIView *last = v;
    
    if (1) {
        UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.contentPanel addSubview:b];
        [b mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(v.mas_bottom).offset(5);
            make.left.equalTo(self.contentPanel).offset(kViewMarginLeft);
            make.width.equalTo(@120);
        }];
        UIImage *img = [UIImage imageNamed:@"ToDo_VoiceBG"];
        [b setBackgroundImage:[img resizableImageWithCapInsets:UIEdgeInsetsMake(0, 25, 0, 10) resizingMode:UIImageResizingModeStretch] forState:UIControlStateNormal];
        
        UILabel *l = [UILabel new];
        [self.contentPanel addSubview:l];
        [l mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(b.mas_right).offset(5);
            make.centerY.equalTo(b);
        }];
        l.text = @"15s";
        l.font = [UIConstants getFont:12];
        l.textColor = [UIColor colorWithRGB:0x828282];
        
        last = b;
    }

    [self.contentPanel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(last.mas_bottom).offset(kViewMarginLeft);
    }];
    
}

- (void)refreshCellPanel{
    [self.cellPanel removeAllSubviews];
    
    ToDoCellView *typeCell = [[ToDoCellView alloc] init];
    [self.cellPanel addSubview:typeCell];
    [typeCell mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.centerX.top.equalTo(self.cellPanel);
        make.height.equalTo(@45);
    }];
    typeCell.titleLabel.text = @"跟进类型";
    typeCell.imageView.image = [UIImage imageNamed:@"CellIcon_TodoTime"];
    
    ToDoCellView *timeCell = [[ToDoCellView alloc] init];
    [self.cellPanel addSubview:timeCell];
    [timeCell mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.centerX.equalTo(self.cellPanel);
        make.height.equalTo(@45);
        make.top.equalTo(typeCell.mas_bottom);
    }];
    timeCell.imageView.image = [UIImage imageNamed:@"CellIcon_TodoType"];
    timeCell.titleLabel.text = @"下次跟进时间";
    
    [self.cellPanel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(timeCell.mas_bottom).offset(kViewMarginLeft);
    }];
}

#pragma mark - Click
- (void)finish{
    
}

- (void)openImagePicker:(UIImagePickerControllerSourceType)type{
    WS(ws);
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = type;
    picker.bk_didFinishPickingMediaBlock = ^(UIImagePickerController *picker, NSDictionary *dictionary){
        UIImage *img = [dictionary objectForKey:UIImagePickerControllerOriginalImage];
        [ws.pictures addObject:img];
        [ws refreshPicturePanel];
        [picker dismissViewControllerAnimated:YES completion:nil];
    };
    
    picker.bk_didCancelBlock = ^(UIImagePickerController *picker){
        [picker dismissViewControllerAnimated:YES completion:nil];
    };
    
    [self.navigationController presentViewController:picker animated:YES completion:nil];
}
@end
